package cn.lock.abstracts.impl;

import cn.lock.abstracts.AbstractAllocatorLock;

import java.util.ArrayList;
import java.util.List;

/**
 * 类简介: 自动锁分配器，必须是单例的才可能实现我们的需求
 * 业务背景：可以使用当前方法来实现锁分配的问题，避免死锁发生（打破占有等待），
 *
 * @Author: ShangGuan
 * @Time: 2024/05/30
 **/
public class WaitLockAllocator extends AbstractAllocatorLock {

    private final List<Object> rootResource = new ArrayList<>();

    @Override
    public synchronized void apply(Object form, Object to) {
        while (rootResource.contains(form) || rootResource.contains(to)) {
            try {
                wait();//同步
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        rootResource.add(form);
        rootResource.add(to);
    }

    /**
     * 释放资源
     **/
    @Override
    public void release(Object form, Object to) {
        rootResource.remove(form);
        rootResource.remove(to);
        notifyAll();
    }
}
